﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectGraph.Core
{
    public class FilteringEnumerator<TDataType> : IEnumerator<TDataType>
    {
        IEnumerator<TDataType> m_enumerator;
        Predicate<TDataType> m_predicate;

        public FilteringEnumerator(IEnumerator<TDataType> enumerator, Predicate<TDataType> predicate)
        {
            m_enumerator = enumerator;
            m_predicate = predicate;
        }


        #region IEnumerator<TDataType> Members

        public TDataType Current
        {
            get { return m_enumerator.Current; }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            m_enumerator.Dispose();
        }

        #endregion

        #region IEnumerator Members

        object System.Collections.IEnumerator.Current
        {
            get { return m_enumerator.Current; }
        }

        public bool MoveNext()
        {
            while (m_enumerator.MoveNext())
            {
                if (m_predicate(m_enumerator.Current))
                    return true;
            }
            return false;
        }

        public void Reset()
        {
            m_enumerator.Reset();
        }

        #endregion
    }

    public class FilteringEnumerable<TDataType> : IEnumerable<TDataType>
    {
        IEnumerable<TDataType> m_enumerable;
        Predicate<TDataType> m_predicate;

        public FilteringEnumerable(IEnumerable<TDataType> enumerable, Predicate<TDataType> predicate)
        {
            m_enumerable = enumerable;
            m_predicate = predicate;
        }



        #region IEnumerable<TDataType> Members

        public IEnumerator<TDataType> GetEnumerator()
        {
            return new FilteringEnumerator<TDataType>(m_enumerable.GetEnumerator(), m_predicate);
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}
